package com.itheima.web;

import com.itheima.bean.User;
import com.itheima.result.R;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody Map<String , String> map, HttpSession session){
        //在session作用域中取出发送个用户的验证码
        //创建存储时的key值
        String key = "login_"+map.get("phone");
        String code = (String) redisTemplate.opsForValue().get(key);
        //String code = (String) session.getAttribute("code");
        //判断验证码是否正确，正确则进行添加操作
        if (code.equalsIgnoreCase(map.get("code"))){
            //登录成功，先进行查询判断查询到的User是否为空，为空则表示是新用户，进行添加操作
            User user = userService.findByPhone(map.get("phone"));
            if (user==null){
                //进入这里表示是新用户，调用service中的添加方法，进行添加用户
                user = userService.add(map.get("phone"));
            }
            //将登录成功的用户对象存进session作用域中
            session.setAttribute("user",user);
            //登录成功返回对应的数据
            return R.success("登录成功！");
        }else {
            //验证码匹配不正确则返回登录失败，请输入正确的验证码
            return R.error("请输入正确的验证码");
        }
    }
}
